const util = require('../../utils/util.js');
const api = require('../../config/api.js');
const user = require('../../services/user.js');
//获取应用实例
const app = getApp()

Page({
    data: {

    },

    getSessionId(){
      wx.login({
        success (res) {
          // 调用 wx.login() 获取 临时登录凭证code ，并回传到开发者服务器。
          console.log(res.code)
          if (res.code) {
            //发起网络请求
            wx.request({
              url: 'http://localhost:8080/miniLogin/getSessionId',
              data: {
                code: res.code
              },
              success(res){
                console.log("返回的map")
                console.log(res.data)
              }
            })
          } else {
            console.log('登录失败！' + res.errMsg)
          }
        }
      })
    },

    getSessionId(){
      wx.login({
        success (res) {
          // 调用 wx.login() 获取 临时登录凭证code ，并回传到开发者服务器。
          console.log(res.code)
          if (res.code) {
            //发起网络请求
            wx.request({
              url: 'http://localhost:8080/miniLogin/getSessionId',
              data: {
                code: res.code
              },
              success(res){
                console.log("返回的map")
                // console.log(res.data.data.sessionId)
                wx.setStorageSync('sessionId', res.data.data.sessionId)
                console.log(wx.getStorageSync('sessionId'))
              }
            })
          } else {
            console.log('登录失败！' + res.errMsg)
          }
        }
      })
    },
    onLoad: function (options) {

    },
    onShow: function () {
      this.getSessionId();

        let userInfo = wx.getStorageSync('userInfo');
        if (userInfo != '') {
            wx.navigateBack();
        };
    },
    // getUserInfo: function (e) {
    //     app.globalData.userInfo = e.detail.userInfo
    //     user.loginByWeixin().then(res => {
    //         app.globalData.userInfo = res.data.userInfo;
    //         app.globalData.token = res.data.token;
    //         let is_new = res.data.is_new;//服务器返回的数据；
    //         if (is_new == 0) {
    //             util.showErrorToast('您已经是老用户啦！');
    //             wx.navigateBack();
    //         }
    //         else if (is_new == 1) {
    //             wx.navigateBack();
    //         }

    //     }).catch((err) => { });
    // },

    getUserProfile: function () {
        // wx.navigateTo({
        //     url: '/pages/app-auth/index',
        // });
        let that = this;
        let code = '';
        wx.login({
            success: (res) => {
                code = res.code;
                wx.request({
                  url: 'https://api.weixin.qq.com/sns/jscode2session?appid=' + 'wx8bc8276e18a9fbbc' + '&secret=' + '17a0e11f2b6665d9142c7977a5d72142' + '&js_code=' + code + '&grant_type=authorization_code',
                  success: function (res) {
                    var openid = res.data.openid //返回openid
                    console.log('openid ===> ' + openid);
                    wx.setStorageSync('od', openid)
                  }
                })
            },   
        });

        // 获取用户信息
        wx.getUserProfile({
            lang: 'zh_CN',
            desc: '用户登录',
            success: (res) => {
                let loginParams = {
                    code: code,
                    encryptedData: res.encryptedData,
                    iv: res.iv,
                    rawData: res.rawData,
                    signature: res.signature
                };
                console.log(loginParams);
                that.postLogin(loginParams);
            },
            // 失败回调
            fail: () => {
                // 弹出错误
                App.showError('已拒绝小程序获取信息');
            }
        });
    },
    postLogin(info) {
      // console.log("info-------------")
      // console.log(info)
      let WXAuth={
        encryptedData:info.encryptedData,
        iv:info.iv,
        sessionId:wx.getStorageSync('sessionId'),
        openId:wx.getStorageSync('od'),
        
      }

      // console.log("wxAuth-------------")
      // console.log(WXAuth)

        util.request(api.AuthLoginByWeixinCL, WXAuth, 'POST').then(function (res) {
            console.log(res);
            if (res.code === 20000) {
                wx.setStorageSync('userInfo', res.data);
                wx.setStorageSync('token', res.data.token);
                app.globalData.userInfo = res.data;
                app.globalData.token = res.data.token;

                wx.navigateBack();
                // let is_new = res.data.is_new; //服务器返回的数据；
                // console.log(is_new);
                // if (is_new == 0) {
                //     util.showErrorToast('您已经是老用户啦！');
                //     wx.navigateBack();
                // } else if (is_new == 1) {
                //     wx.navigateBack();
                // }
            }
        });
    },
    goBack: function () {
        wx.navigateBack();
    }
})